//
//  PayWebViewController.m
//  HuiKaoClient
//
//  Created by Wang Li on 13-3-9.
//  Copyright (c) 2013年 龚 杰. All rights reserved.
//

#import "PayWebViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "AppDelegate.h"
#import "LoginViewController.h"
#import "MainTabBarController.h"
#import "PayOkViewController.h"
@interface PayWebViewController ()

@end

@implementation PayWebViewController
@synthesize m_OderIDStr;
- (id)init
{
    if (self = [super init]) {
        // Custom initialization
    }
    return self;
}

-(void) dealloc
{
    [m_OderIDStr release];
    [m_titleBttBarItem release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
//    UILabel* tNavTitleLab = (UILabel*)[self.navigationController.navigationBar viewWithTag:144];
//    [tNavTitleLab setText:@"订单提交"];
    m_titleBttBarItem = [[MainTabBarController setTitle:@"订单提交"] retain];
    
    _NavBtt = [UIButton buttonWithType:UIButtonTypeCustom];
    [_NavBtt setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [_NavBtt addTarget:self action:@selector(navPopPressed) forControlEvents:UIControlEventTouchUpInside];
    _NavBtt.frame =CGRectMake(4, 7, 50, 30);
    [_NavBtt retain];
    UILabel* tBackLab = [[UILabel alloc] initWithFrame:CGRectMake(14, 5, 30, 20)];
    [tBackLab setBackgroundColor:[UIColor clearColor]];
    [tBackLab setTextColor:[UIColor whiteColor]];
    [tBackLab setText:@"返回"];
    [tBackLab setFont:[UIFont systemFontOfSize:13]];
    [_NavBtt addSubview:tBackLab];
    [tBackLab release];
    
    [self requestDetailData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar addSubview:_NavBtt];
}
-(void) viewWillDisappear:(BOOL)animated
{
    [_NavBtt removeFromSuperview];
}

-(void) navPopPressed
{
    [self.navigationController popViewControllerAnimated:YES];
}


-(void) requestAddChartFinish:(ASIHTTPRequest*)request
{
    NSError* tError;
    NSString* tReqStr = [request responseString];
    NSLog(@"ads json data =%@",tReqStr);
    NSData *jsonData = [tReqStr dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&tError];
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    if (tDataDic != nil) {
        int tErrorCode =[[tDataDic objectForKey:@"error_code"] intValue];
        if (tErrorCode == 0) {
            NSDictionary* tRealDic = [tDataDic objectForKey:@"data"];
            _PayURL = [tRealDic objectForKey:@"pay_url"];
            [_PayURL retain];
            
            _CallBack = [tRealDic objectForKey:@"callback"];
            [_CallBack retain];
            
            UIWebView*  tWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height-44)];
            tWebView.delegate = self;
            [tWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_PayURL]]];
            [self.view addSubview:tWebView];
            [tWebView release];
        }else{
            if ([tDataDic objectForKey:@"error_msg"] != nil) {
                [tAppDel showWithCustomView:[tDataDic objectForKey:@"error_msg"] detailText:@"" isCue:-1 delayTime:2];
            }else{
                [tAppDel showWithCustomView:@"数据错误" detailText:@"" isCue:YES delayTime:2];
            }
            
        }
    }
    [self hudWasHidden:nil];
}

-(void) requestDetailData
{
    [self addHudLoad];
    NSString* tURLStr = [NSString stringWithFormat:@"%@ac=pay&order_id=%@",RequestCurrentURL,m_OderIDStr];
    
    tURLStr = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)tURLStr, nil, nil, kCFStringEncodingUTF8);
    ASIHTTPRequest* tRequestPage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tURLStr]];
    [tRequestPage setDelegate:self];
    [tRequestPage setDidFailSelector:@selector(requestDetailFail:)];
    [tRequestPage setDidFinishSelector:@selector(requestAddChartFinish:)];
    [tRequestPage startAsynchronous];
    
}

-(void) requestDetailFail:(ASIHTTPRequest*)request
{
    AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [tAppDel showWithCustomView:@"网络错误" detailText:@"" isCue:YES delayTime:2];
    [self hudWasHidden:nil];
}

#pragma mark -
#pragma mark MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud{
	[_MBHUD removeFromSuperview];
    _MBHUD.delegate = nil;
	[_MBHUD release];
	_MBHUD=nil;
}

-(void) addHudLoad{
	if (_MBHUD == nil) {
		_MBHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
		// Add HUD to screen
		[self.navigationController.view addSubview:_MBHUD];
		// Regisete for HUD callbacks so we can remove it from the window at the right time
		_MBHUD.delegate = self;
		_MBHUD.labelText = @"请求数据中...";
		[_MBHUD show:YES];
	}
}

#pragma mark-
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.absoluteString rangeOfString:_CallBack].location != NSNotFound) {
        NSLog(@"%@",request.URL.absoluteString);
        int tCutStart = [request.URL.absoluteString rangeOfString:@"?"].location;
        NSString* tSubStr = [request.URL.absoluteString substringWithRange:NSMakeRange(tCutStart+1, [request.URL.absoluteString length]-tCutStart-1)];
        NSLog(@"%@",tSubStr);
        NSArray* tClipArr = [tSubStr componentsSeparatedByString:@"&"];
        NSString* tMsg = nil;
        NSString* tStatus = nil;
        for (NSString* tContent in  tClipArr) {
            NSArray* tKeys = [tContent componentsSeparatedByString:@"="];
            if ([[tKeys objectAtIndex:0] isEqualToString:@"status"]) {
                tStatus = [tKeys objectAtIndex:1];
            }else if([[tKeys objectAtIndex:0] isEqualToString:@"msg"]) {
                tMsg = [tKeys objectAtIndex:1];
                tMsg =[tMsg stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            }
        }
        AppDelegate* tAppDel = (AppDelegate*)[UIApplication sharedApplication].delegate;
        if ([tStatus isEqualToString:@"sucess"]) {
            PayOkViewController* tPayOKVC = [[PayOkViewController alloc]
                                             init];
            tPayOKVC.navigationItem.hidesBackButton =YES;
            //[self.navigationController popViewControllerAnimated:NO];
            [self.navigationController pushViewController:tPayOKVC animated:YES];
            [tPayOKVC release];
            return YES;
        }else{
            [tAppDel showWithCustomView:tMsg detailText:@"" isCue:-1 delayTime:2];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
    return YES;
}

@end
